package com.whimscrew.user.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Objects;

@EnableFeignClients
@Configurable
public class FeignConfig implements RequestInterceptor {


    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 请求转出调用其他微服务前，设置传递token
     * 还需在请求的serveice配置这个类, 项目为：DeptService，才能成功转出
     * @param template RequestTemplate
     */
    @Override
    public void apply(RequestTemplate template) {
        //假设集成Hystrix，attributes就会受到Hystrix隔离机制影响，导致变为null，需要自定义Hystrix配置
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        if(Objects.isNull(attributes)){
            return ;
        }
        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                template.header(name, values);

            }
            logger.info("======= feign interceptor header:{}",template);
        }
    }


}
